package com.mbatis.produerConsumer;

/**
 * 生产者消费者实现方式1 wait/notify方式
 *
 * TODO  同步代码块中 包含了 wait() 和 notify()
 */
public class PcTest1 {

    private static Integer count = 0;
    private static final Integer FULL = 10;
    private static String LOCK = "lock";

    public static void main(String[] args) {
        PcTest1 pcTest1 = new PcTest1();
//        new Thread(pcTest1.new Producer()).start();
        new Thread(pcTest1.new Consumer()).start();
//        new Thread(pcTest1.new Producer()).start();
//        new Thread(pcTest1.new Consumer()).start();
    }


    class Producer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (LOCK){
                    while (count == FULL){
                        try {
                           LOCK.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName()+"生产者生产，目前总共有 "+count);
                    LOCK.notifyAll();
                }
            }
        }
    }


    class Consumer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (LOCK){
                    while(count == 0){
                        try {
                            LOCK.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName()+"消费者消费，目前总共有 "+count);
                    LOCK.notifyAll();
                }
            }
        }
    }


}


